//
//  MainViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/21.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "MainViewController.h"
#import "RentVieitor.h"
#import "RecommendCell.h"
#import "ProblemCell.h"
#import "AgentViewController.h"
#import "HouseDetailViewController.h"
#import "RentHouseViewController.h"
#import "BuildingViewController.h"
#import "RentalinformationVC.h"
#import "WeiTuoChuZuVc.h"
#import "FangModel.h"
#import "MJRefresh.h"
#import "NewsModel.h"
#import "StrategyViewController.h"

@interface MainViewController ()<UITextFieldDelegate,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@end

@implementation MainViewController {
    
    UIImageView *bannerview;
    UITableView *_tableView;
}

#define IMAGE_HEIGHT    KWidth*340/750

- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:223/250.0 green:128/255.0 blue:31/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[Utils colorConvertFromString:@"#333333"]}];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    [APPDELEGATE createGuidancePage];
}

- (void)viewDidLoad {
    

    [super viewDidLoad];
    self.title = @"首页";
    self.fangData = [NSMutableArray array];
    self.newsData = [NSMutableArray array];
    [self creatLeftView];
    [self creatNavigationView];
    [self creatView];
    [self loadData];
    [self loadNewData];
    
    
}

- (void)creatNavigationView {
    
    //搜索视图
    UIView *naView = [[UIView alloc] init];
    naView.layer.masksToBounds = YES;
    naView.layer.cornerRadius = 2.5;
    naView.backgroundColor = [UIColor whiteColor];
    naView.frame = CGRectMake(30, 55, KWidth-60, 30);
    
    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectBtn.frame = CGRectMake(0,0, 70, 30);
    selectBtn.tag = 100;
    selectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [selectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 30)];
    [selectBtn setImageEdgeInsets:UIEdgeInsetsMake(5, 40, 0, 0)];
    [selectBtn setTitleColor:[Utils colorConvertFromString:@"#101010"] forState:UIControlStateNormal];
    [selectBtn setTitle:@"深圳" forState:UIControlStateNormal];
    //    [selectBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    [selectBtn setImage:[UIImage imageNamed:@"三角形"] forState:UIControlStateNormal];
    [naView addSubview:selectBtn];
    
    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(60, 0, naView.frame.size.width-60, 30)];
    field.delegate = self;
    field.font = [UIFont systemFontOfSize:14];
    field.leftViewMode = UITextFieldViewModeAlways;
    [naView  addSubview:field];
    field.placeholder = @"请输入小区名称或者地址";
    self.navigationItem.titleView = naView;
    UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    imgview.image = [UIImage imageNamed:@"搜索icon"];
    field.leftView = imgview;
    
}

- (void)loadData {
    
    NSString *url = [NSString stringWithFormat:@"%@fang/list/recommend",Main_Url];
    NSDictionary *dic = @{
                          @"category":@"1001",
                          @"city":@"103",
                          @"rows":[NSString stringWithFormat:@"%d",3]
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSLog(@"%@========",str);
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSLog(@"%@---",md5String);

    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                
                [Utils nullDic:dic];
                FangModel *model = [[FangModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [WeakSelf.fangData addObject:model];
            }
            
            [_tableView   reloadData];
            [_tableView.mj_header endRefreshing];
        
        }
        
        
    } failure:^(NSError *err) {
        
        [_tableView.mj_header endRefreshing];
    }];

}

- (void)loadNewData {
    
    NSString *url = [NSString stringWithFormat:@"%@news/list",Main_Url];
    NSDictionary *dic = @{
                          @"type":@"1",
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSLog(@"str:%@",str);
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    NSLog(@"md5String:%@",md5String);
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSLog(@"md5String:%@",md5String);

    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            
            
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                
                [Utils nullDic:dic];
                NewsModel *model = [[NewsModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [WeakSelf.newsData addObject:model];
            }
            
            [_tableView   reloadData];
            
            [_tableView.mj_header endRefreshing];

        }
        
        
    } failure:^(NSError *err) {
        
        [_tableView.mj_header endRefreshing];

    }];

}

- (void)creatView {
    
    CGFloat margin = 30;
    CGFloat marginH = 15;
    CGFloat width = (KWidth-margin*5)/4;
    CGFloat heigt = width + 15;
    
    UIView *serveView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth-20, IMAGE_HEIGHT+marginH*3+heigt*2-20)];
    serveView.backgroundColor = BackgroundColor;
    
    //banner
    bannerview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth, IMAGE_HEIGHT)];
    bannerview.image = [UIImage imageNamed:@"banner2"];
    bannerview.contentMode = UIViewContentModeScaleAspectFill;
    bannerview.layer.masksToBounds = YES;
    [serveView addSubview:bannerview];
    
    
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(10, IMAGE_HEIGHT-20, KWidth-20, marginH*3+heigt*2)];
    bgView.backgroundColor = [UIColor whiteColor];
    [serveView addSubview:bgView];
    
    NSArray *imgArray = @[@"租房",@"经纪人",@"商铺",@"写字间",@"委托出租",@"找小区",@"生活服务",@"攻略"];
    NSArray *titleArray = @[@"房源信息",@"经纪人",@"商铺",@"写字间",@"找小区",@"求租信息",@"委托出租",@"攻略"];
    
    for (int i=0; i<titleArray.count; i++) {
        
        UIControl *control = [[UIControl alloc] initWithFrame:CGRectMake(i%4*width+(i%4+1)*margin, i/4*heigt+(i/4+1)*marginH+IMAGE_HEIGHT-20, width, heigt)];
        control.tag = 100+i;
        control.userInteractionEnabled = YES;
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(5,5,width-10,width-10)];
        imgView.image = [UIImage imageNamed:imgArray [i]];
        [control addSubview:imgView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(-5, width, width+10, 20)];
        label.text = titleArray[i];
        label.textColor = [Utils colorConvertFromString:@"#101010"];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        [control addSubview:label];
        
        [control addTarget:self action:@selector(serveAction:) forControlEvents:UIControlEventTouchUpInside];
        [serveView addSubview:control];
        
    }
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight-49) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = BackgroundColor;
    _tableView.tableHeaderView  = serveView;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];

    [_tableView registerClass:[RecommendCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerClass:[ProblemCell class] forCellReuseIdentifier:@"cell2"];
    [self.view addSubview:_tableView];
    
    
}

-(void)headerRefresh{
    
    [self.fangData removeAllObjects];
    [self.newsData removeAllObjects];
    
    if (self.fangData == nil) {
        self.fangData = [NSMutableArray array];
    }
    
    if (self.newsData == nil) {
        self.newsData = [NSMutableArray array];
    }
    [self loadNewData];
    [self loadData];
    
    
}

#pragma mark -- 协议方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        if ( self.fangData.count >= 3) {
            return 3;
        }
        return self.fangData.count;
    }else {
        if ( self.newsData.count >= 2) {
            return 2;
        }
        return self.newsData.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
    
        RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        if (self.fangData.count > indexPath.row) {
            cell.model = self.fangData[indexPath.row];
        }
        
        return cell;
    }else if(indexPath.section == 1) {
        
        ProblemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        if (self.newsData.count > indexPath.row) {
            cell.model = self.newsData[indexPath.row];
        }
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 55;
    }else if (section == 1){
        return KWidth*346/750+55;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        HouseDetailViewController *houseVc = [[HouseDetailViewController alloc] init];
        FangModel *model = self.fangData[indexPath.row];
        houseVc.sn = model.sn;
        [self.navigationController pushViewController:houseVc animated:YES];
    }
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 55)];
        sectionView.backgroundColor = BackgroundColor;
        
        UILabel *recommend = [[UILabel alloc] initWithFrame:CGRectMake(15, 12.5, 150, 30)];
        recommend.text = @"推荐房源";
        recommend.font = [UIFont systemFontOfSize:15];
        recommend.textColor = [Utils colorConvertFromString:@"#101010"];
        recommend.textAlignment = NSTextAlignmentLeft;
        [sectionView addSubview:recommend];
        
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeSystem];
        moreButton.frame = CGRectMake(KWidth-60, 20, 60, 15);
        [moreButton setTitle:@"更多 >" forState:UIControlStateNormal];
        [moreButton setTitleColor:[Utils colorConvertFromString:@"#999999"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
        moreButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [sectionView addSubview:moreButton];
        return sectionView;
        
    }else if (section == 1) {
        
        CGFloat height = KWidth*346/750+55;
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, height)];
        sectionView.backgroundColor = BackgroundColor;
        
        UILabel *psp = [[UILabel alloc] initWithFrame:CGRectMake(15, 12.5, 150, 30)];
        psp.text = @"租房攻略";
        psp.font = [UIFont systemFontOfSize:15];
        psp.textColor = [Utils colorConvertFromString:@"#101010"];
        psp.textAlignment = NSTextAlignmentLeft;
        [sectionView addSubview:psp];
        
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeSystem];
        moreButton.frame = CGRectMake(KWidth-60, 20, 60, 15);
        [moreButton setTitle:@"更多 >" forState:UIControlStateNormal];
        [moreButton setTitleColor:[Utils colorConvertFromString:@"#999999"] forState:UIControlStateNormal];
        moreButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [sectionView addSubview:moreButton];
        [moreButton addTarget:self action:@selector(newsMoreAction) forControlEvents:UIControlEventTouchUpInside];
       
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 55, KWidth, height-55)];
        img.image = [UIImage imageNamed:@"img_03"];
        
        UILabel *whiteLabel = [[UILabel alloc] initWithFrame:CGRectMake(12.5, height-40-55, KWidth-12.5, 30)];
        whiteLabel.text = @"当您租房时,应该注意哪些问题呢?";
        whiteLabel.font = [UIFont systemFontOfSize:15];
        whiteLabel.textColor = [UIColor whiteColor];
        whiteLabel.textAlignment = NSTextAlignmentLeft;
        [img addSubview:whiteLabel];
        
        [sectionView addSubview:img];
        
        return sectionView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 100;
}

- (void)serveAction:(UIControl *)control {
    
//    @"租房",@"找小区",@"经纪人",@"写字间",@"商铺",@"委托出租",@"生活服务",@"攻略"
    if (control.tag == 100) {
        
        //租房
        RentHouseViewController *rentVc = [[RentHouseViewController alloc] init];
        [self.navigationController pushViewController:rentVc animated:YES];
        return;
    }
    
    if (control.tag == 101) {
        
        //找小区
        AgentViewController *agentVc = [[AgentViewController alloc] init];
        [self.navigationController pushViewController:agentVc animated:YES];
        return;
    }
    
    if (control.tag == 102) {
        
        //找小区
        RentHouseViewController *rentVc = [[RentHouseViewController alloc] init];
        [self.navigationController pushViewController:rentVc animated:YES];
        return;
        
    }
    
    if (control.tag == 103) {
        
        //写字间
        RentHouseViewController *rentVc = [[RentHouseViewController alloc] init];
        [self.navigationController pushViewController:rentVc animated:YES];
        return;
        
    }
    if (control.tag == 104) {
        
        //委托出租
        BuildingViewController *rentVc = [[BuildingViewController alloc] init];
        [self.navigationController pushViewController:rentVc animated:YES];
        
        
    }
    if (control.tag == 105){
        //求租信息
        RentalinformationVC    *InforVc = [[RentalinformationVC alloc]init];
        [self.navigationController pushViewController:InforVc animated:YES];
    }
    if (control.tag == 106) {
        WeiTuoChuZuVc *weituoVc = [[WeiTuoChuZuVc alloc]init];
        weituoVc.titleStr = @"委托出租";
        [self presentViewController:weituoVc animated:YES completion:nil];
    }
    if (control.tag == 107) {
        
        //攻略
        StrategyViewController *rentVc = [[StrategyViewController alloc] init];
        [self.navigationController pushViewController:rentVc animated:YES];
        return;
    }
    
//    [APPDELEGATE showPro:@"功能完善中"];
    
//     if (control.tag == 103) {
//        
//        //写字间
//        BuildingViewController *rentVc = [[BuildingViewController alloc] init];
//        [self.navigationController pushViewController:rentVc animated:YES];
//
//        
//    }
//    
//   

//        else if (control.tag == 105) {
//
//        //委托出租
//        BuildingViewController *rentVc = [[BuildingViewController alloc] init];
//        [self.navigationController pushViewController:rentVc animated:YES];
//
//    }else if (control.tag == 106) {
//        
//        //生活服务
//        BuildingViewController *rentVc = [[BuildingViewController alloc] init];
//        [self.navigationController pushViewController:rentVc animated:YES];
//
//    }else if (control.tag == 107) {
//        
//        //攻略
//        BuildingViewController *rentVc = [[BuildingViewController alloc] init];
//        [self.navigationController pushViewController:rentVc animated:YES];
//
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.1;
}

- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(-10, 0, 20,20 );
    leftBtn.enabled = NO;
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"用户-(1)"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(mainAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
}

- (void)mainAction {
    
    
}

- (void)newsMoreAction {
    
    [APPDELEGATE showPro:@"功能完善中"];
}

- (void)moreAction {
    
    RentHouseViewController *rentVc = [[RentHouseViewController alloc] init];
    [self.navigationController pushViewController:rentVc animated:YES];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    RentHouseViewController *rentVc = [[RentHouseViewController alloc] init];
    [self.navigationController pushViewController:rentVc animated:YES];
    return NO;
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    
//    CGFloat y = scrollView.contentOffset.y;
//    NSLog(@"%f",y);
//    if (y < -(IMAGE_HEIGHT+64)) {
//        CGRect frame = bannerview.frame;
//        frame.origin.y = y+64;
//        frame.size.height =  -y-64;
//        bannerview.frame = frame;
//    }
//    
//}

@end
